package lewiszlw.sso.server.util;

import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @ClassName CommonUtil
 * @Description: 常用的工具类
 * @Author yezhiqiang
 * @Date 2019/12/5
 * @Version V1.0
 **/
public class CommonUtil {
    /**
     * 签名规则校验
     * 1.校验时间戳
     * 2.进行字典排序
     * 3.进行sha256加密,比较
     *
     * @param signature
     * @param token。有度税智提供的发货token，用于验签
     * @param timestamp
     * @param eventId
     * @return
     */
    public static Boolean checkTxySignature(String signature, String token, long timestamp, String eventId) {
        //1.校验时间是否过期
        long currentTime = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        if (currentTime - timestamp > 300000) {
            return false;
        }
        //2.进行字典排序
        List<String> params = new ArrayList<>();
        params.add(eventId);
        params.add(String.valueOf(timestamp));
        params.add(token);
        Collections.sort(params);
        String localSignature = StringUtils.join(params, "");
        //3.进行sha256加密,比较
        localSignature = CommonUtil.sha256(localSignature);
        return StringUtils.equals(localSignature, signature);
    }

    /**
     * @param str
     * @return
     * @throws Exception
     */
    public static String sha256(String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            return byte2Hex(messageDigest.digest());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("sha256加密异常");
        }
    }

    /**
     * @param digest
     * @return
     */
    private static String byte2Hex(byte[] digest) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < digest.length; i++) {
            temp = Integer.toHexString(digest[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    public static void main(String[] args) {
        Long timestamp = System.currentTimeMillis();
        System.out.println(timestamp);
        List<String> params = new ArrayList<>();
        params.add("111");
        params.add(String.valueOf(timestamp));
        params.add("7s2h3843hjj290726khsnn782ns0s76ss");
        Collections.sort(params);
        String localSignature = StringUtils.join(params, "");
        //3.进行sha256加密,比较
        System.out.println(CommonUtil.sha256(localSignature));
    }
}
